<?php
namespace api\modules\v1\models;

use api\components\ApiModel;
use common\models\ARChat;
use common\models\AROrder;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * 留言板模型
 * @author ZCY
 */
class Chat extends ApiModel
{
    const SCENARIO_SEND = 'send';
    const SCENARIO_LIST = 'list';

    public static $messages = [
        'accept_need'            => ['message' => '%s加入了广告。'],
        'select-broker'          => ['message' => '%s选择了%s经纪人加入了广告。'],
        'change-broker'          => ['message' => '%s更改了%s经纪人加入了广告。'],
        'confirm-order'          => ['message' => '%s同意了交易。'],
        'refuse-order'           => ['message' => '%s拒绝了交易。'],
        'confirm-payment'        => ['message' => '%s已经付款。'],
        'confirm-receive'        => ['message' => '%s已经收款。'],
        'confirm-receive_finish' => ['message' => '%s已经收款。恭喜本次广告交易完成，请互相评价！'],
    ];

    public $order_id;
    public $message;
    public $size;

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'order_id' => '订单编号',
            'message'  => '消息内容',
            'size'     => '显示的留言条数',
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        return [
            self::SCENARIO_SEND => ['order_id', 'message'],
            self::SCENARIO_LIST => ['order_id', 'size'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['order_id', 'message'], 'trim'],
            [['order_id', 'message'], 'required'],
            ['order_id', 'orderCheck', 'on' => [self::SCENARIO_SEND]],
            ['size', 'default', 'value' => '100'],

        ];
    }

    /**
     * 订单编号检测
     * @param $attribute
     * @param $params
     */
    public function orderCheck($attribute, $params)
    {
        $orderInfo = AROrder::findOne(['id' => $this->attributes]);
        if (!$orderInfo) {
            $this->addError($attribute, '订单号不合法!');
        } else {
            $uid = Yii::$app->user->id;
            if ($orderInfo->uid !== $uid && $orderInfo->opp_uid !== $uid && $orderInfo->broker !== $uid) {
                $this->addError($attribute, '订单号不合法!');
            }
        }
    }

    /**
     * 发送留言信息
     */
    public function send()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }

        $chat = new ARChat();
        $userInfo = $this->getUser(Yii::$app->user->id);

        $chat->uid = $userInfo->id;
        $chat->unickname = $userInfo->nickname;
        $chat->order_id = $this->order_id;
        $chat->message = $this->message;
        $chat->type = ARChat::TYPE_USER;
        if (!$chat->save()) {
            self::getErrorMessge($chat);
        }

        return ['nickname' => $userInfo->nickname, 'content' => $this->message];
    }

    /**
     * 留言列表信息
     */
    public function chatlist()
    {
        if (!$this->validate()) {
            self::getErrorMessge($this);
        }
        $chatmodel = ARChat::find()->where(['order_id' => $this->order_id]);
        $count = $chatmodel->count();
        if ($count <= $this->size) {
            $rows = $chatmodel->all();
        } else {
            $rows = $chatmodel->offset($count - $this->size)->limit($this->size)->all();
        }

        $rows = ArrayHelper::toArray($rows, [
            ARChat::className() => [
                'id',
                'unickname',
                'message',
                'created_at' => function ($row) {
                    return Yii::$app->formatter->asDateTime($row->created_at);
                },
                'issender'   => function ($row) {
                    return $row->uid === Yii::$app->user->id ? 1 : 0;
                },
                'type',
            ],
        ]);
        return ['count' => $count, 'list' => $rows];
    }

    /**
     * 添加留言消息(系统)
     * @param  unknown   $userInfo
     * @param  unknown   $order_id
     * @param  unknown   $message_type
     * @param  string    $brokerInfo
     * @return boolean
     */
    public static function addSystemMessage($userInfo, $order_id, $message_type, $brokerInfo = null)
    {
        if (!isset(self::$messages[$message_type])) {
            self::throwError('600001');
        }
        $message = '';
        $chat = new ARChat();
        $chat->order_id = $order_id;
        $chat->type = ARChat::TYPE_SYSTEM;
        switch ($message_type) {
            case 'select-broker':
            case 'apply-broker':
                $message = sprintf(self::$messages[$message_type]['message'], $userInfo->nickname, $brokerInfo->nickname);
                break;

            default:
                $message = sprintf(self::$messages[$message_type]['message'], $userInfo->nickname);
        }
        $chat->message = $message;
        if (!$chat->save()) {
            self::getErrorMessge($chat);
        }
        return true;
    }

    /**
     * 添加留言消息(用户)
     * @param unknown $userInfo
     * @param unknown $order_id
     * @param unknown $message
     */
    public function addUserMessage($userInfo, $order_id, $message)
    {
        $chat = new ARChat();

        $chat->uid = $userInfo->id;
        $chat->unickname = $userInfo->nickname;
        $chat->order_id = $order_id;
        $chat->message = $message;
        $chat->type = ARChat::TYPE_USER;
        if (!$chat->save()) {
            self::getErrorMessge($chat);
        }
        return true;
    }

}
